package com.blackhorse.controller;

import com.blackhorse.domain.Account;
import com.blackhorse.domain.UserB;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Spring MVC请求参数绑定
 */
@Controller
@RequestMapping("/param")
public class ParamController {
    /**
     * 请求参数入门
     * 方法参数名与请求参数名相同时，spring mvc可以自动获得请求参数值
     *
     * @return 转发的jsp页面
     */
    @RequestMapping("/testParam")
    public String testParam(String username, String password) {
        System.out.println("获取请求参数：username=" + username);
        System.out.println("获取请求参数：password=" + password);
        return "success";
    }

    /**
     * 把请求参数封装为JavaBean
     * 包括基本类型（springmvc会自动识别常用的java类型并封装）的封装和引用类型的封装
     *
     * @return 转发的jsp页面
     */
    @RequestMapping("/saveAccount")
    public String saveAccount(Account account) {
        System.out.println("封装好的Account对象：" + account);
        System.out.println("\tAccount对象中封装的User对象：" + account.getUser());
        System.out.println("\tAccount对象中封装的List<User>对象：" + account.getUsers());
        System.out.println("\tAccount对象中封装的Map<String, User>对象：" + account.getUserMap());
        return "success";
    }

    /**
     * 使用自定义类型转换器
     * 日期类型默认支持 yyyy/MM/dd 格式
     * <p>
     * 为了自定义转换成yyyy-MM-dd格式，需要编写Converter接口的实现类，并在springmvc.xml文件中配置
     *
     * @param user
     * @return
     */
    @RequestMapping("/saveUser")
    public String saveUser(UserB user) {
        System.out.println("封装的User对象：" + user);
        return "success";
    }

    /**
     * 获取Servlet原生API
     * 只需要在参数中加上HttpServletRequest和HttpServletResponse
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/testServlet")
    public String testServlet(HttpServletRequest request, HttpServletResponse response) {
        System.out.println(request);
        System.out.println(response);
        HttpSession session = request.getSession();//获取session
        System.out.println(session);
        ServletContext servletContext = session.getServletContext();//获取servletContext
        System.out.println(servletContext);
        return "success";
    }
}
